<template>
    <div class="white-box">
        <div class="table-mb">
            <el-button type="primary" @click="addLabel">添加</el-button>
            <el-button type="default" plain @click="allDel">批量删除</el-button>
        </div>
        <div class="task-one">
            <div class="task-one__item">
                <span class="task-one__label">标签名称：</span>
                <el-input placeholder="输入标签名称搜索" v-model.trim="search_text" clearable></el-input>
            </div>
            <div class="task-one__btn clearfix">
                <el-button type="primary" :loading="search_btn" :icon="Search" @click="handleSearch">搜索</el-button>
            </div>
        </div>

        <el-table
            class="table-mb"
            v-loading="loading"
            :data="arr_data"
            :header-cell-style="{ background: '#F5F7FA' }"
            element-loading-background="rgba(255, 255, 255, 0.6)"
            @selection-change="handleAllSelected"
        >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="tag_id" label="标签ID" width="100"></el-table-column>
            <el-table-column prop="title" label="标签名称" min-width="180"></el-table-column>
            <el-table-column label="背景色" width="120">
                <template #default="{ row }">
                    <span class="sku-span" :style="{ background: row.color }"></span>
                </template>
            </el-table-column>
            <el-table-column label="排序" min-width="130">
                <template #default="{ row }">
                    <el-input
                        v-model.trim="row.order_by"
                        clearable
                        placeholder="请输入排序数字"
                        oninput="value=value.replace(/[^\d]/g,'')"
                        style="width: 100px"
                        @change="() => inputSort(row)"
                    />
                </template>
            </el-table-column>
            <el-table-column prop="created_at_label" label="添加时间" width="220"> </el-table-column>
            <el-table-column label="操作" width="240" class-name="operation-nav" fixed="right">
                <template #default="{ row }">
                    <el-button link type="primary" class="theme-btn" @click="clickEdit(row)">编辑 </el-button>
                    <el-popconfirm title="是否确定删除？" confirm-button-text="确定" cancel-button-text="取消" @confirm="clickDel(row)">
                        <template #reference>
                            <el-button link type="primary" class="theme-btn">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
            background
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="pageSizeNum"
            :total="totalNums"
            layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>

        <!-- 添加/编辑 -->
        <el-dialog
            v-model="dialogLabel"
            :title="labelType == 1 ? '添加标签' : '编辑标签'"
            width="560px"
            :append-to-body="true"
            :destroy-on-close="true"
            @close="closeLabel"
        >
            <el-form ref="ruleLabelRef" :model="ruleLabelForm" :rules="ruleCheckLabel" label-width="120px">
                <el-form-item label="标签名称" prop="name">
                    <el-input v-model.trim="ruleLabelForm.name" clearable placeholder="请输入标签名称" />
                </el-form-item>
                <el-form-item label="颜色RGB" prop="color_rgb" required>
                    <el-tooltip class="box-item" effect="dark" content="右侧选择颜色值" placement="top-start">
                        <el-input v-model="ruleLabelForm.color_rgb" placeholder="请点击右侧选择颜色值" clearable>
                            <template #append>
                                <el-color-picker v-model="ruleLabelForm.color_rgb" size="default" />
                            </template>
                        </el-input>
                    </el-tooltip>
                </el-form-item>
                <el-form-item label="排序" prop="sort" required>
                    <el-input v-model.number="ruleLabelForm.sort" clearable oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入排序数字" />
                </el-form-item>
                <el-form-item>
                    <div class="flexs" style="margin-top: 30px">
                        <el-button type="primary" :loading="form_loading" @click="submitForm(ruleLabelRef)">
                            {{ labelType == 1 ? "确认添加" : "确认修改" }}
                        </el-button>
                        <el-button @click="resetForm(ruleLabelRef)">重置</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>

        <go-back />
    </div>
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, watch, reactive,onBeforeUnmount } from "vue"
import OneLoad from "@mixins/one-load"
import { Search } from "@element-plus/icons-vue"
import GoBack from "@components/GoBack.vue"

const { proxy } = getCurrentInstance()

onMounted(() => {
    getList()
})

onBeforeUnmount(() => {
   
})

/**
 * minxin列表加载
 */
const { page, pageSizeNum, pageSize, loading, arr_data, search_btn, search_text, totalNums, pubParams, pubRefreshParams, getdata } = OneLoad()

// 切换每页显示条数
watch(pageSize, (val) => {
    page.value = 1
    pubParams(getList)
})
// 跳转第几页
watch(page, (val) => {
    pubParams(getList)
})

const handleSearch = () => {
    search_btn.value = true
    pubRefreshParams(getList)
}

function getList() {
    let params = {
        page: page.value,
        limit: pageSize.value,
        so: search_text.value,
    }
    getdata("supplier/tag/index", params)
}

/**
 * 添加/编辑
 * @property {Boolean} dialogLabel 添加/编辑弹窗状态
 * @property {Boolean} form_loading 提交按钮状态
 * @property {Number} labelType 弹窗类型，1是添加，2是编辑
 * @property {Array} ruleLabelRef 表单规则
 * @property {Object} ruleLabelForm  表单字段
 * @property {Object} ruleCheckLabel  表单提示
 * @property {Function} submitForm 提交表单
 */
const dialogLabel = ref(false)
const form_loading = ref(false)
const labelType = ref(1)
const ruleLabelRef = ref(null)
const ruleLabelForm = reactive({
    id: "",
    name: "",
    sort: "100",
    color_rgb: "#409EFF",
})
const ruleCheckLabel = reactive({
    name: [{ required: true, message: "请输入颜色名称", trigger: "blur" }],
    sort: [{ required: true, message: "请输入排序数字", trigger: "blur" }],
    color_rgb: [{ required: true, message: "请选择背景颜色", trigger: "change" }],
})
const submitForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            form_loading.value = true
            let data = {
                title: ruleLabelForm.name,
                color: ruleLabelForm.color_rgb,
                order_by: ruleLabelForm.sort,
            }

            if (labelType.value == 2) {
                data.tag_id = ruleLabelForm.id
            }
            let url = labelType.value == 1 ? "supplier/tag/add" : "supplier/tag/update"
            proxy.$axios
                .post(url, data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        dialogLabel.value = false
                        proxy.$message({ message: `${labelType.value == 1 ? '添加成功！' : '编辑成功！'}`, type: "success" })
                        pubParams(getList)
                    } else {
                        proxy.$message({message:res.data.msg,type:"error"})
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
const closeLabel = () => {
    dialogLabel.value = false
    resetForm(ruleLabelRef.value)
}

// 添加
const addLabel = () => {
    labelType.value = 1
    dialogLabel.value = true
}

// 编辑
const clickEdit = (row) => {
    dialogLabel.value = true
    setTimeout(() => {
        ruleLabelForm.name = row.title
        ruleLabelForm.sort = row.order_by
        ruleLabelForm.color_rgb = row.color
        labelType.value = 2
        ruleLabelForm.id = row.tag_id
    }, 50)
}

// 删除单个
const clickDel = (row) => {
    postDel(row.tag_id)
}
// 删除多个
const ids = ref([])
const handleAllSelected = (val) => {
    let arrs = []
    for (let i = 0; i < val.length; i++) {
        arrs.push(val[i].tag_id)
    }
    ids.value = arrs
}
const allDel = () => {
    if (ids.value.length == 0) {
        proxy.$message({ message: "请选择需要删除的数据", type: "warning" })
        return
    }
    postDel(ids.value)
}
// 删除接口
function postDel(params) {
    proxy.$axios
        .post("supplier/tag/delete", {
            tag_id: params,
        })
        .then((res) => {
            if (res.data.code == 0) {
                pubParams(getList)
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {})
}

// 排序
const inputSort = (row) => {
    if (!row.order_by) {
        proxy.$message({ message: "请输入排序数字", type: "warning" })
        return
    }
    proxy.$axios
        .post("supplier/tag/sort", {
            tag_id: row.tag_id,
            order_by: row.order_by,
        })
        .then((res) => {
            if (res.data.code == 0) {
                pubParams(getList)
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {})
}
</script>
<script>
export default {
    name: "LabelManaget",
}
</script>

<style lang="less" scoped>
.sku-span {
    width: 20px;
    height: 20px;
    display: inline-block;
    margin-left: @margin-base;
}
</style>
